﻿using LJH.SmartAlarmSystem.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LJH.SmartAlarmSystem.UControls
{
    public partial class URoundedButton : Button
    {
        /// <summary>
        /// 存储按钮的客户区矩形（Client Rectangle），用于计算圆角路径（GraphicsPath）
        /// </summary>
        private Rectangle _clientRect;
        public URoundedButton()
        {
            InitializeComponent();

            #region 设置控件样式标志
            SetStyle(ControlStyles.Selectable, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);     // 忽略窗口消息，减少闪烁
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);    // 绘制到缓冲区，减少闪烁
            SetStyle(ControlStyles.UserPaint, true);                // 控件由其自身而不是操作系统绘制
            SetStyle(ControlStyles.ResizeRedraw, true);             // 控件调整其大小时重绘
            SetStyle(ControlStyles.SupportsTransparentBackColor, true); // 支持透明背景
            #endregion

            _clientRect = this.ClientRectangle;

            #region 其他配置，不确定是否启用，暂注释
            // 设置背景色透明（Button类自带）
            this.BackColor = Color.Transparent;

            // 去除按钮边框（Button类自带）
            this.FlatStyle = FlatStyle.Flat;
            this.FlatAppearance.BorderSize = 0;
            this.FlatAppearance.MouseDownBackColor = Color.Transparent;
            this.FlatAppearance.MouseOverBackColor = Color.Transparent;
            #endregion
        }

        #region 属性扩展：主背景色、次背景色、背景色渐变模式、边框粗细、边框颜色、点击后的文字颜色、圆角半径、文本边距
        /// <summary>
        /// 圆角按钮的主背景颜色
        /// </summary>
        [DefaultValue(typeof(Color), "Gray")]
        [Description("设置圆角按钮的主背景颜色，默认为灰色")]
        public Color PrimaryBackgroundColor
        {
            get { return _primaryBackgroundColor; }
            set
            {
                _primaryBackgroundColor = value;
                Invalidate();
            }
        }
        private Color _primaryBackgroundColor = Color.Gray;

        /// <summary>
        /// 圆角按钮的次背景颜色，默认为透明。当该属性被设置为其他颜色时，按钮背景将显示从主背景色到次背景色的渐变效果
        /// </summary>
        [DefaultValue(typeof(Color), "Transparent")]
        [Description("设置圆角按钮的次背景颜色，默认为透明。当该属性被设置为其他颜色时，按钮背景将显示从主背景色到次背景色的渐变效果")]
        public Color SecondaryBackgroundColor
        {
            get { return _secondaryBackgroundColor; }
            set
            {
                _secondaryBackgroundColor = value;
                Invalidate();
            }
        }
        private Color _secondaryBackgroundColor = Color.Transparent;

        /// <summary>
        /// 圆角按钮背景颜色的渐变方向，默认为垂直渐变，仅在次背景颜色被设置时生效
        /// </summary>
        [DefaultValue(typeof(LinearGradientMode), "Vertical")]
        [Description("设置背景颜色的渐变方向，默认为垂直渐变，仅在次背景颜色被设置时生效")]
        public LinearGradientMode BackgroundGradientMode
        {
            get { return _backgroundGradientMode; }
            set
            {
                _backgroundGradientMode = value;
                Invalidate();
            }
        }
        private LinearGradientMode _backgroundGradientMode = LinearGradientMode.Vertical;

        /// <summary>
        /// 圆角按钮的边框粗细（单位：像素）
        /// </summary>
        [DefaultValue(typeof(int), "0")]
        [Description("设置圆角按钮的边框粗细（单位：像素）")]
        public int BorderWidth
        {
            get { return _borderWidth; }
            set 
            { 
                _borderWidth = value;
                Invalidate();
            }
        }
        private int _borderWidth = 0;

        /// <summary>
        /// 圆角按钮的边框颜色，默认为灰色
        /// </summary>
        [DefaultValue(typeof(Color), "Gray")]
        [Description("设置圆角按钮的边框颜色，默认为灰色")]
        public Color BorderColor
        {
            get { return _borderColor; }
            set
            {
                _borderColor = value;
                Invalidate();
            }
        }
        private Color _borderColor = Color.Gray;

        /// <summary>
        /// 圆角按钮被选中(点击？TODO)后的文本颜色
        /// </summary>
        [DefaultValue(typeof(Color), "Red")]
        [Description("设置圆角按钮被选中(点击？TODO)后的文本颜色")]
        public Color SelectedTextColor
        {
            get { return _selectedTextColor; }
            set
            {
                _selectedTextColor = value;
                Invalidate();
            }
        }
        private Color _selectedTextColor = Color.Red;

        /// <summary>
        /// 圆角按钮的圆角半径（单位：像素），0表示直角
        /// </summary>
        [DefaultValue(typeof(int), "5")]
        [Description("设置圆角按钮的圆角半径（单位：像素），0表示直角")]
        public int RoundRadius
        {
            get { return _roundRadius; }
            set
            {
                _roundRadius = Math.Max(0, value); // 确保不小于0
                Invalidate();
            }
        }
        private int _roundRadius = 5;

        /// <summary>
        /// 获取或设置文本与背景矩形边缘的距离（单位：像素）
        /// </summary>
        [DefaultValue(typeof(Padding), "2,2,2,2")]  // 明确指定默认值结构
        [Description("控制文本内容与背景矩形四边的间距，影响布局对齐效果")]
        public Padding TextPadding
        {
            get => _textPadding;
            set
            {
                if (_textPadding != value)
                {
                    _textPadding = value;
                    Invalidate();  // 触发重绘以应用新边距
                }
            }
        }
        private Padding _textPadding = new Padding(2);
        #endregion

        #region 焦点相关
        /// <summary>
        /// 重写ShowFocusCues属性，禁用控件默认的焦点视觉提示（如虚线框）
        /// </summary>
        protected override bool ShowFocusCues
        {
            get { return false; } // 始终返回false表示不显示系统自带的焦点提示
        }

        /// <summary>
        /// 标记鼠标按下状态的私有字段，用于区分焦点变化是否由鼠标操作触发
        /// </summary>
        private bool _isMouseDown = false;

        /// <summary>
        /// 重写OnGotFocus方法，处理控件获得焦点时的逻辑
        /// </summary>
        /// <param name="e">事件参数</param>
        protected override void OnGotFocus(EventArgs e)
        {
            base.OnGotFocus(e);     // 必须调用基类方法确保基础焦点逻辑执行
            _isMouseDown = true;    // 标记鼠标按下状态
        }

        /// <summary>
        /// 重写OnLostFocus方法，处理控件失去焦点时的逻辑
        /// </summary>
        /// <param name="e">事件参数</param>
        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);    // 必须调用基类方法确保基础焦点逻辑执行
            _isMouseDown = false;   // 清除鼠标状态标记
        }
        #endregion

        #region 控件重绘相关
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            _clientRect = this.ClientRectangle;
            this.Region = new Region(_clientRect);
            _clientRect.Width -= 1;
            _clientRect.Height -= 1;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);                             // 调用基类方法确保基础焦点逻辑执行
            Graphics g = e.Graphics;                     // 获取绘图对象
            g.SmoothingMode = SmoothingMode.HighQuality; // 绘制内容包含​​缩放图像或渐变​​，优先用HighQuality

            // 1. 计算圆弧半径
            int borderRadius = _roundRadius;
            int backgroundRadius = Math.Max(_roundRadius - _borderWidth, 0);

            // 2. 计算矩形区域
            Rectangle borderRect = _clientRect;                         // 边框的矩形绘制区域
            Rectangle backgroundRect = new Rectangle(
                _clientRect.X + _borderWidth,
                _clientRect.Y + _borderWidth,
                Math.Max(_clientRect.Width - 2 * _borderWidth, 0),
                Math.Max(_clientRect.Height - 2 * _borderWidth, 0));    // 背景的矩形绘制区域

            // 3. 生成路径
            GraphicsPath borderPath = PaintClass.GetRoundedRectangle(borderRect, borderRadius);                 // 边框的圆角矩形路径
            GraphicsPath backgroundPath = PaintClass.GetRoundedRectangle(backgroundRect, backgroundRadius);     // 背景的圆角矩形路径
            
            // 4. 绘制边框
            if (_borderWidth > 0)
            {
                using (Brush borderBrush = new SolidBrush(_borderColor))
                {
                    g.FillPath(borderBrush, borderPath);
                }
            }

            // 5. 绘制背景
            using (Brush backgroundBrush = _secondaryBackgroundColor != Color.Transparent
                ? new LinearGradientBrush(backgroundRect, _primaryBackgroundColor, _secondaryBackgroundColor, _backgroundGradientMode)
                : new SolidBrush(_primaryBackgroundColor))
            {
                g.FillPath(backgroundBrush, backgroundPath);
            }

            // 6. 绘制文本
            Rectangle textRect = new Rectangle(
                backgroundRect.X + _textPadding.Left,
                backgroundRect.Y + _textPadding.Top,
                backgroundRect.Width - _textPadding.Horizontal,
                backgroundRect.Height - _textPadding.Vertical
            );
            using (StringFormat format = new StringFormat
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            })
            using (Brush fontBrush = new SolidBrush(_isMouseDown ? _selectedTextColor : this.ForeColor))
            {
                g.DrawString(Text, this.Font, fontBrush, textRect, format);
            }
        }
        #endregion
    }
}
